package com.lei.springbootpractice3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lei.springbootpractice3.mapper.UserMapper;
import com.lei.springbootpractice3.pojo.UsersPojo;
import com.lei.springbootpractice3.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


import java.beans.Encoder;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserMapper userMapper;
    @Override
    public boolean register(UsersPojo usersPojo){
        QueryWrapper<UsersPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",usersPojo.getUsername());
        boolean usernameExists=userMapper.selectCount(queryWrapper)>0;
        if(usernameExists){
            return false;
        }else{
            usersPojo.setPassword(passwordEncoder.encode(usersPojo.getPassword()));
            userMapper.insert(usersPojo);
            return true;
        }
    }

    @Override
    public UsersPojo login(String username,String password){
        QueryWrapper<UsersPojo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        UsersPojo usersPojo = userMapper.selectOne(queryWrapper);
        if(usersPojo!=null&&passwordEncoder.matches(password,usersPojo.getPassword())){
            return usersPojo;
        }else{
            return null;
        }
    }

}
